package admin

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/constants"
	"gozero-demo/internal/model/dao/model"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type UpdateUserExtraDataLogic struct {
	logx.Logger
	ctx      context.Context
	svcCtx   *svc.ServiceContext
	userRepo *mysql.UserRepo
}

// 更新用户扩展数据
func NewUpdateUserExtraDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserExtraDataLogic {
	return &UpdateUserExtraDataLogic{
		Logger:   logx.WithContext(ctx),
		ctx:      ctx,
		svcCtx:   svcCtx,
		userRepo: mysql.NewUserRepo(ctx, svcCtx),
	}
}

func (l *UpdateUserExtraDataLogic) UpdateUserExtraData(req *types.UpdateUserExtraDataRequest) (resp *types.CommonResponse, err error) {
	//校验当前数据是否存在
	existInfo, err := l.userRepo.GetUserInfo(req.Id)
	if err != nil {
		return nil, err
	}
	if existInfo == nil {
		return nil, constants.UserDataNotFound
	}

	// ExtraData 转 json
	extraData, err := json.Marshal(req.ExtraData)
	if err != nil {
		logx.Errorf("extraData json.Marshal err: %v", err)
		return nil, err
	}

	//更新数据
	updateData := &model.User{
		Extra: string(extraData),
	}
	_, err = l.userRepo.UpdateUser(updateData, req.Id, nil)
	if err != nil {
		return nil, err
	}

	return types.SuccessResponseEmpty(l.ctx), nil
}
